package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;


@Service
@Slf4j
public class ApUserLoginServiceImpl implements ApUserLoginService {
    @Autowired
    private ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDTO dto) {
        //判断传过来的设备id是否正常
        if (dto.getEquipmentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断输入的用户名和密码是否为空
        if (StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotBlank(dto.getPassword())) {
            //根据手机号查询账户是否存在
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getStatus, 0).eq(ApUser::getPhone, dto.getPhone()));
            if (apUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "请输入正确手机号");
            }
            //获取查出来的密码
            String password = apUser.getPassword();
            //进行MD5加密
            String newPassword = DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes());
            if (!password.equals(newPassword)) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "密码错误");
            }

            HashMap<String, Object> map = new HashMap<>();
            apUser.setPassword("");
            apUser.setSalt("");
            //将用户id进行jwt,并返回token
            map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
            map.put("userId", apUser);
            return ResponseResult.okResult(map);
        } else {
            //如果为空
            HashMap<String, Object> map = new HashMap<>();
            //将jwt储存为0
            map.put("token", AppJwtUtil.getToken(0l));
            return ResponseResult.okResult(map);
        }
    }
}